import sys,io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
import time
import requests
#from lxml import etree
from bs4 import BeautifulSoup
import pymysql
from random import randint, sample

def generate_red_num():

    red_balls = [x for x in range(1, 34)]

    selected_balls = sorted(sample(red_balls, 6))

    #print(selected_balls)

    return str(selected_balls)

def generate_blue_num():

    blue_ball = [y for y in range(1,17)]

    selected_blueball = sample(blue_ball, 1)

    #print(selected_blueball)

    return str(selected_blueball)

def generate_date():

    lottery_date = time.strftime('%Y-%m-%d', time.localtime(time.time()))

    return lottery_date

def issue_number():
    
    url = 'http://kaijiang.zhcw.com/zhcw/html/ssq/list.html'
    response = requests.get(url).text
    soup = BeautifulSoup(response, 'lxml')
    issue = soup.select('tr')[2:3][0].select('td')[1].text
    #print(issue)
    return issue


def save_to_database():

    database = pymysql.connect(host='localhost', user='root', passwd='', db='lottery', charset='utf8')
    cursor = database.cursor()
    #check the issue info in database
    cursor.execute('select issue from ssq_my')
    issue_db = cursor.fetchall()
    list_issue_db = list(issue_db)
    #print(list_issue_db)
    
    # next issue should +1
    issue = int(issue_number()) + 1

    #check if next issue had already insert to database
    if str(issue) == list(list_issue_db[-1])[0]:
        print('已经随机过本期号码,随机号码为： ')

        cursor.execute('select red from ssq_my where issue='+str(issue))
        red_db = cursor.fetchone()
        print('红球： '+list(red_db)[0])
        
        cursor.execute('select blue from ssq_my where issue='+str(issue))    
        blue_db = cursor.fetchone()
        print('蓝球： '+list(blue_db)[0])
        
        print('期号： '+str(issue))
        cursor.close()
    else:
        red_ball = generate_red_num()
        blue_ball = generate_blue_num()
        print('本期随机号码为：')
        print('红球： '+ red_ball)
        print('蓝球： '+ blue_ball)
        print('期号： '+ str(issue))
    
        #insert to database
        insert_DB = "insert into ssq_my " +"(issue,red,blue) values(%s,%s,%s)"
        values = (issue,red_ball,blue_ball)

        cursor.execute(insert_DB,values)
        cursor.close()


    cursor.close()
    database.commit()
    database.close()


def main():
    #wechat()
    #get_info()
    save_to_database()
    #generate_red_num()
    #generate_blue_num()
    #issue_number()

if __name__ == '__main__':
    main()
